package com.diy.sigmund.diyorder.common.spring.config;

/**
 * @author ylm-sigmund
 * @since 2021/11/7 18:12
 */

import com.diy.sigmund.diycommon.entity.constant.HeaderConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * <br>Feign配置
 * <br>使用FeignClient进行服务间调用，传递headers信息
 * <br>还需要修改hytrix隔离策略：https://www.yht7.com/news/158716
 *
 * @author ylm
 * @see <a href="https://blog.csdn.net/m0_37701381/article/details/82023076">Spring Boot Feign服务调用之间带token
 */
@Configuration
public class FeignHeaderInterceptor implements RequestInterceptor {

    private static final Logger log = LoggerFactory.getLogger(FeignHeaderInterceptor.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("为当前请求添加内部调用请求头");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // xxl-job进入做feign调用会报NPE
        if (Objects.nonNull(attributes)) {
            HttpServletRequest request = attributes.getRequest();
        }
        // 添加token
        requestTemplate.header(HeaderConstant.INNER_TOKEN, HeaderConstant.INNER_TOKEN_VALUE);
    }
}